<?php
/*
 * @thinkphp3.2.2  auth认证   php5.3以上
 * @Created on 2015/08/18
 * @Author  夏日不热(老屁)   757891022@qq.com
 *
 */
namespace Admin\Controller;
use Common\Controller\AuthController;
use Think\Auth;

//后台会员
class UserController extends AuthController
{

	private $groupId = 51;//分组id
	private $Public_pid='10000000';//默认收益账号

	//用户列表
	public function user_list(){
		$info = M('User');
		$member=M('member','vip_');
		if(($_GET['mobile']) != null){
			$mobile = $_GET['mobile'];
			$data = array('mobile'=>array("like","%".$mobile."%"));
			$count = $info->where($data)->count();
			$Page = new \Think\Page($count,10);
			$show = $Page->show();// 分页显示输出
			$list = $info->field('id,mobile,create_time,type,realname,add_jf_currency,add_jf_limit')->where($data)->limit($Page->firstRow.','.$Page->listRows)->select();
		}else{
			$count = $info->count();
			$Page = new \Think\Page($count,10);
			$show = $Page->show();// 分页显示输出
			$list = $info->field('id,mobile,create_time,type,realname,add_jf_currency,add_jf_limit')->limit($Page->firstRow.','.$Page->listRows)->select();
		}
		foreach($list as $k=>$v){
			$grade=$member->where(array('id'=>$v['id']))->getfield('grade_name');
			$vip_end=$member->where(array('id'=>$v['id']))->getfield('vip_end');
			//echo $member->getLastSql();
			$list[$k]['grade_name']=$grade;
			$list[$k]['vip_end']=$vip_end;
		}
		//dump($list);exit;
		$this->assign('list',$list);
		$this->assign('page',$show);
		$this->display();
		
	}
	
	
	//用户详情
	public function user_view(){
		$id = $_GET['id'];
		$info = M('User');
		$result = $info->where(array('id'=>$id))->find();
		$this->assign('result',$result);
		$this->display();
	}
	
	/**
	 * 会员列表
	 */
	public function m_list()
	{
		$m = M('user');
		$nowPage = isset($_GET['p']) ? $_GET['p'] : 1;
		//实现带查询条件的分页,get方式传参
		$num = $_REQUEST['keyword'];
		$type = $_REQUEST['type'];
		$num = trim($num);
		if ($num != "") {
			if ($type == 1) {
				$where = array('a.mobile' => array("like", "%" . $num . "%"), 'a.status' => 1);
			} else {
				$where = array('a.id' => $num, 'a.status' => 1);
			}
		} else {
			$where = array('a.status' => 1);
		}
		$where[]=array('grade_name'=>'会员');
		// page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
		$data = $m->order('a.id DESC')->field("a.*,b.grade_name,b.user_id,b.pid,b.path")->join('as a Left join db_member as b on a.id=b.user_id')->where($where)->page($nowPage . ',' . PAGE_SIZE)->select();
		//dump($m->getLastSql());
		//dump($num);
		//dump($m->getLastSql());exit;
		foreach ($data as $k => $v) {
			$data[$k]['create_time'] = date('Y-m-d H:i:s', $data[$k]['create_time']);
		}
		//分页
		if (array_key_exists("a.id", $where)) {
			$count = 1;
		} else {
			$count = $m->order('a.id DESC')->field("a.*,b.grade_name,b.user_id,b.pid,b.path")->join('as a Left join db_member as b on a.id=b.user_id')->where($where)->count();        // 查询满足要求的总记录数
		}
		//dump($m->getLastSql());
		$page = new \Think\Page($count, PAGE_SIZE);        // 实例化分页类 传入总记录数和每页显示的记录数PAGE_SIZE
		$page->parameter['keyword'] = $num;
		$page->parameter['type'] = $_REQUEST['type'] ? $_REQUEST['type'] : 0;
		$show = $page->show();        // 分页显示输出
		$this->assign('page', $show);// 赋值分页输出
		$this->assign('data', $data);
		$this->assign('head_title', '会员');
		$this->display('user_list');
	}
public function getMid($user_id){
	return M('member')->where(array('user_id'=>$user_id))->getField('id');
}
	//删除用户
	public function user_del()
	{
		$m = M('user');
		$password = I("post.password");
		$model = M("admin");
		$member=M('member');
		$m->startTrans();
		$admin_id=$m->where(array("id" => I("post.id")))->getField('admin_id');
		$member_id=$member->where(array("admin_id" => $admin_id))->getField('id');
		$pwd = $model->where(array("id" => session('aid')))->getField("password");
		if ($pwd != md5($password)) {
			$this->ajaxReturn(2);
			exit;
		}
		if (!is_array(I("post.id"))) {
			$where['id'] = I("post.id");    //活动ID
			$result1 = $m->where(array("id" => $where['id']))->delete();
			$result2=$member->where(array("admin_id" => $admin_id))->delete();
			$result3=$model->where(array("id" => $admin_id))->delete();
			if(M('member_profit')->where(array("member_id" => $member_id))->count()>0){
				M('member_profit')->where(array("member_id" => $member_id))->delete();
			}
			//file_put_contents("1.txt",$m->getLastSql());
		}
		if ($result1 && $result2 && $result3) {
			$m->commit();
			$this->ajaxReturn(1);
		} else {
			$m->rollback();
			$this->ajaxReturn(0);
		}
	}

	//收藏列表
	public function collect_list()
	{
		$m = M('Collect');
		$nowPage = isset($_GET['p']) ? $_GET['p'] : 1;

		// page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
		$data = $m->order('id DESC')->page($nowPage . ',' . PAGE_SIZE)->select();
		//分页
		$count = $m->where()->count(id);        // 查询满足要求的总记录数
		$page = new \Think\Page($count, PAGE_SIZE);        // 实例化分页类 传入总记录数和每页显示的记录数
		$show = $page->show();        // 分页显示输出
		$this->assign('page', $show);// 赋值分页输出
		$this->assign('data', $data);
		$this->display();
	}

	//发送优惠券
	public function coupons_add()
	{
		if (!empty($_POST)) {
			$m = M('user_coupons');
			//$_POST['mobile'] = $_COOKIE['mobile'];
			$_POST['create_time'] = time();
			$result = $m->add($_POST);
			if ($result) {
				$this->success('发送成功');
			} else {
				$this->error('发送失败');
			}
		} else {
			$result['begin_date'] = date('Y-m-d', time() + 86400);
			$result['end_date'] = date('Y-m-d', time() + 86400 * 7);
			$this->assign('result', $result);
			$this->display();
		}
	}

	
	
	//优惠卷列表‘
	public function coupons_list(){
		$mobile = I('get.mobile');
		$where = array();
		if($mobile!=''){
			$where['mobile'] = trim($mobile);
		}
		$used_status = I('get.use_status');
		if($used_status !==''){
			if($used_status==1){
				$where['use_status'] = 1;
			}else{
				$where['use_status'] = 0;
			}
		}
		$m = M('user_coupons');
		$count= $m->where($where)->count();
		$Page  = new \Think\Page($count,20);
		$show = $Page->show();
		$res = $m->where($where)->order('id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
		$this->assign('result', $res);
		$this->assign('page', $show);// 赋值分页输出
		$this->display();

	}

	//删除优惠券
	public function coupons_del()
	{
		$where['id'] = $_POST['id'];    //活动ID
		$m = M('user_coupons');
		$result = $m->where($where)->delete();
		if ($result) {
			$data['code'] = '1';    //删除成功
			$this->ajaxReturn($data);
		} else {
			$data['code'] = '0';    //删除失败
			$this->ajaxReturn($data);
		}
	}

	//关于我们
	public function about_us()
	{
		if (!empty($_POST)) {
			$m = M('page');
			$where['columu'] = 'about_us';    //栏目名称
			$_POST['update_time'] = time();    //更新时间
			$result = $m->where($where)->save($_POST);
			if ($result) {
				$this->success('保存成功');
			} else {
				$this->error('保存失败');
			}
		} else {
			$m = M('page');
			$where['columu'] = 'about_us';    //栏目名称
			$result = $m->where($where)->find();
			$this->assign('result', $result);
			$this->display();
		}
	}

	//我的特权
	public function my_tequan()
	{
		if (!empty($_POST)) {
			$m = M('page');
			$where['columu'] = 'my_tequan';    //栏目名称
			$_POST['update_time'] = time();    //更新时间
			$result = $m->where($where)->save($_POST);
			if ($result) {
				$this->success('保存成功');
			} else {
				$this->error('保存失败');
			}
		} else {
			$m = M('page');
			$where['columu'] = 'my_tequan';    //栏目名称
			$result = $m->where($where)->find();
			$this->assign('result', $result);
			$this->display();
		}
	}

	//短信管理
	public function user_sms_list()
	{
		$m = M('user_sms');
		if (!empty($_POST['mobile'])) {
			$where['mobile'] = $_POST['mobile'];    //手机号
		}
		$nowPage = isset($_GET['p']) ? $_GET['p'] : 1;
		$result = $m->where($where)->order('id DESC')->page($nowPage . ',' . PAGE_SIZE)->select();
		//分页
		$count = $m->where($where)->count(id);        // 查询满足要求的总记录数
		$page = new \Think\Page($count, PAGE_SIZE);        // 实例化分页类 传入总记录数和每页显示的记录数
		$show = $page->show();        // 分页显示输出
		$this->assign('page', $show);// 赋值分页输出
		$this->assign('data', $result);
		$this->display();
	}

	//删除短信记录
	public function user_sms_del()
	{
		$where['id'] = $_POST['id'];    //短信记录ID
		$m = M('user_sms');
		$result = $m->where($where)->delete();
		if ($result) {
			$this->ajaxReturn(1);    //删除成功
		} else {
			$this->ajaxReturn(0);
		}
	}

	/**
	 * 个人中心
	 */
	public function user_middle()
	{
		$this->display("user_middle");
	}

	/**
	 * 个人中心编辑
	 */
	 public function user_edit()
	{
		$m = D('member');
		$user = D('user');
		if (IS_AJAX) {
			//echo 9;exit;
			$where = array("user_id" => I("post.id"));
			$newpid = I('post.pid');
			$password = I('post.password');
			$model = M('admin');
			$TruePassword = $model->where(array("id" => session('aid')))->getField('password');
			if (md5($password) != $TruePassword) {
//				权限密码错误
				echo 1;
				exit;
			}
//			if (M("user")->where(array('id' => $newpid))->count() == 0 && $newpid != 0) {
////				不存在的上级ID
//				echo 2;
//				exit;
//			}
			//$oldpid = $m->where($where)->getfield('pid');
			//$oldpath=$m->where($where)->getField('path');
			//$parent_path=$m->where(array('id'=>$oldpid))->getField('path');
			//$mobile=I('post.mobile');
			$parent_path=$m->where(array('id'=>$newpid))->getField('path');
			$usergrade = I('post.grade');
			if ($usergrade == 1) {
				$usergrade = "合伙人";
			} else {
				$usergrade = "会员";
			}
			$newpath =$parent_path.R('User/getMid',array(I("post.id"))).'-';
			//循环数据库重新设置下线的path
			$allPath=$m->where(array('pid'=>R('User/getMid',array(I("post.id")))))->select();
			foreach($allPath as $avalue){
				if(substr_count($avalue['path'],'-'.R('User/getMid',array(I("post.id"))).'-')>0){
					$arr=explode('-'.R('User/getMid',array(I("post.id"))).'-',$avalue['path']);
					//$newpath.$arr[1];新的路径
					$m->where(array('id'=>$avalue['id']))->save(array('path'=>$newpath.$arr[1]));
				}
			}
			//$newpath = $this->Public_pid."-" . $newpid . "-" . R('User/getMid',array(I("post.id"))) . '-';
			$m->startTrans();
			$rst = $m->where($where)->save(array('path' => $newpath, "grade_name" => $usergrade, "pid" => $newpid,
				'true_name' => I('post.true_name'),
				'email' => I('post.email'),
				'bankid' => I('post.bankid'),
				'kaihuhang' => I('post.kaihuhang'),
				'mobile' => I('post.mobile'),
				'card_id' => I('post.card_id'),
				'bankid' => I('post.bankid'),
				'addr' => I('post.addr'),
				'zip_code' => I('post.zip_code'),
				'vip_end' => strtotime(I('post.vip_end')),
				));
			$user->where(array('id'=>I("post.id")))->save(array('mobile'=>null));
			$send=$user->where(array('id'=>I("post.id")))->save(array('mobile'=>I('post.mobile')));
			//file_put_contents("1.txt",$m->getLastSql());
//				修改成功
			if ($rst && $send) {
				$m->commit();
				echo 9;
				exit;
			} else {
//				//出错了
				$m->rollback();
				echo 0;
				exit;
			}
		} else {
			$model = D('user');
			$where = array("a.id" => I("get.id"));
			$data = $model->field("a.*,b.grade_name,b.user_id,b.pid,b.path")->join('as a Left join db_member as b on a.id=b.user_id')->where($where)->find();
			$data['member']=$m->where(array('user_id'=> I("get.id")))->find();
			$this->assign('user', $data);
			$this->display();
		}

	}
	/* public function user_edit2()
	{
		$m = D('member');
		$user = D('user');
		if (IS_AJAX) {
			//echo 9;exit;
			$where = array("user_id" => I("post.id"));
			$newpid = I('post.pid');
			$password = I('post.password');
			$model = M('admin');
			$TruePassword = $model->where(array("id" => session('aid')))->getField('password');
			if (md5($password) != $TruePassword) {
//				权限密码错误
				echo 1;
				exit;
			}
//			if (M("user")->where(array('id' => $newpid))->count() == 0 && $newpid != 0) {
////				不存在的上级ID
//				echo 2;
//				exit;
//			}
			$oldpid = $m->where($where)->getfield('pid');
			//$oldpath=$m->where($where)->getField('path');
			//$mobile=I('post.mobile');
			$usergrade = I('post.grade');
			if ($usergrade == 1) {
				$usergrade = "合伙人";
			} else {
				$usergrade = "会员";
			}
			$newpath = $this->Public_pid."-" . $newpid . "-" . R('User/getMid',array(I("post.id"))) . '-';
			$m->startTrans();
			$rst = $m->where($where)->save(array('path' => $newpath, "grade_name" => $usergrade, "pid" => $newpid,
				'true_name' => I('post.true_name'),
				'email' => I('post.email'),
				'bankid' => I('post.bankid'),
				'kaihuhang' => I('post.kaihuhang'),
				'mobile' => I('post.mobile'),
				'card_id' => I('post.card_id'),
				'bankid' => I('post.bankid'),
				'addr' => I('post.addr'),
				'zip_code' => I('post.zip_code'),
				'vip_end' => strtotime(I('post.vip_end')),
				));
			$user->where(array('id'=>I("post.id")))->save(array('mobile'=>null));
			$send=$user->where(array('id'=>I("post.id")))->save(array('mobile'=>I('post.mobile')));
			//file_put_contents("1.txt",$m->getLastSql());
//				修改成功
			if ($rst && $send) {
				$m->commit();
				echo 9;
				exit;
			} else {
//				//出错了
				$m->rollback();
				echo 0;
				exit;
			}
		} else {
			$model = D('user');
			$where = array("a.id" => I("get.id"));
			$data = $model->field("a.*,b.grade_name,b.user_id,b.pid,b.path")->join('as a Left join db_member as b on a.id=b.user_id')->where($where)->find();
			$data['member']=$m->where(array('user_id'=> I("get.id")))->find();
			$this->assign('user', $data);
			$this->display();
		}

	} */


	/**
	 * @param $id
	 * 删除邀请人,归为平台所属
	 */
	public function removeParent()
	{
		if (IS_AJAX) {
			$m = D('member');
			$password = I("post.password");
			$id = I("post.id");
			$model = M("admin");
			$mid=$m->where(array("user_id" => I("post.id")))->getField("id");
			$pwd=$model->where(array("id" => session('aid')))->getField("password");
			if ($pwd != md5($password)) {
				$this->ajaxReturn(1);
				exit;
			}
			$data = array('pid' => $this->Public_pid, 'path' => $this->Public_pid.'-'.$mid.'-');
			$rst = $m->where(array("user_id" => $id))->save($data);
			//file_put_contents('1.txt',$m->getLastSql());
			if ($rst) {
				$this->ajaxReturn(9);
			} else {
				$this->ajaxReturn(0);
			}
		}
	}

	/**
	 * 修改用户等级
	 */
	public function upGrade()
	{
		$m = D('member');
		if (IS_POST) {
			$id = I('post.id');
			$grade = I('post.grade');
			if (in_array($grade, array('合伙人', '会员'))) {
				$data = array('usergrade' => $grade);
				$rst = $m->where(array('id' => $id))->save($data);
				if ($rst) {
					$this->success('修改成功');
				} else {
					$this->error('修改失败');
				}
			}
		}
	}

//	public function chongzhi($id, $money)
//	{
//		//获取上级数组
//		$m = M('member');
//		$str = $m->where(array('id' => $id))->getField('path');
//		$len = substr_count($str, "@") - 1 >= 0 ? substr_count($str, "@") : 0;
//		//判断上级类型
//		if ($len == 1) {
//			//只有1级
//			$this->situation1($id, $money);
//		} elseif ($len == 2) {
//			//只有2级
//			$this->situation2($id, $money);
//		} elseif ($len >= 3) {
//			//3级以及3级以上
//			$this->situation3($id, $money);
//		} else {
//			exit;
//		}
//	}
//
//	protected function situation1($id, $money)
//	{
//		if ($this->getParentType($id) == "合伙人") {
//			$percentage = 0.3;//父级为合伙人的百分比
//		} else {
//			//判断自身是不是合伙人，会员的下家不能是合伙人
//			if ($this->getSelfType($id) == "合伙人") {
//				exit("会员的下级不能是合伙人");
//			}
//			$percentage = 0.1;//父级为会员的百分比
//		}
//		$money *= $percentage;
//		$this->addMoney($id, $money, 1);
//	}
//
//	protected function situation2($id, $money)
//	{
//		$this->situation1($id, $money);
//		//如果爷级为会员
//		if ($this->getParentType($id, 2) == "会员") {
//			$percentage = 0.1;//爷级为会员的百分比
//		} else if ($this->getParentType($id, 2) == "合伙人") { //如果爷级为合伙人
//			$percentage = 0.1;//爷级为合伙人的百分比
//		}
//		$money *= $percentage;
//		$this->addMoney($id, $money, 2);
//	}
//
//	protected function situation3($id, $money)
//	{
//		$this->situation2($id, $money);
//		//如果爷级为会员
//		if ($this->getParentType($id, 3) == "会员") {
//			$percentage = 0.1;//祖级为会员的百分比
//		} else
//			//如果爷级为合伙人
//			if ($this->getParentType($id, 3) == "合伙人") {
//				$percentage = 0.1;//祖级为合伙人的百分比
//			}
//		$money *= $percentage;
//		$this->addMoney($id, $money, 3);
//	}
//
//	/**
//	 * @param int $id 父级需要增加Money的id
//	 * @param int $proportion 增加的百分比
//	 * * @param int $p 为谁增加 1=父亲，2=爷爷，3=祖父
//	 */
//	protected function addMoney($id, $money = 0, $p = 1)
//	{
//		$m = M('member');
//		for ($i = 0; $i < $p; ++$i) {
//			if ($i == 0) {
//				$pid = $id;
//			}
//			$pid = $this->getPid($pid);
//		}
//		$m->where(array("id" => $pid))->setInc("money", $money);
//	}
//
//	/**
//	 * @param $id
//	 * * @param $p循环查找上级次数
//	 * 查询父级的类型
//	 */
//	public function getParentType($id, $p = 1)
//	{
//		$m = M('member');
//		for ($i = 0; $i < $p; ++$i) {
//			if ($i == 0) {
//				$pid = $id;
//			}
//			$pid = $this->getPid($pid);
//		}
//		return $m->where(array("id" => $pid))->getField("usergrade");
//	}

	/**
	 * @param $id
	 * 查询父级ID
	 */
	public function getPid($id)
	{
		$m = M('member');
		$pid = $m->where(array("id" => $id))->getField('pid');
		return $pid;
	}

	/**
	 * @param $id
	 * 根据自己的id查询出父级姓名
	 * @return mixed
	 */
	public function getParentName($id)
	{
		$m = D('member');
		//$mid=$this->getMid($id);
		$pid = $m->where(array("user_id" => $id))->getField('pid');
		if($pid==1 || $pid ==0 || $pid==''){
			return "平台";
		}
		$ParentName = $m->where(array("id" => $pid))->getField('true_name');
		return $ParentName;
	}

	public function isPidExist()
	{
		$arr = array();
		if (IS_AJAX) {
			if (I('post.pid') == 1) {
				$arr['status'] = 1;
				$arr['msg'] = "平台";
				$this->ajaxReturn($arr);
				exit;
			} else {
				$newpid = I('post.pid');
				$vip = I('post.grade_name');
				if (M("member")->where(array('id' => $newpid))->getField('grade_name') == "会员" && $vip == 1) {
					$arr['status'] = 2;
					$arr['msg'] = "合伙人的上级不能为会员.";
					$this->ajaxReturn($arr);
					exit;
				}
				$user_id = M('member')->where(array('id' => $newpid))->getField('user_id');
				if (M("user")->where(array('id' => $user_id))->count() == 0 && $newpid != 0) {
//				不存在的上级ID
					$arr['status'] = 0;
					$arr['msg'] = "";
					$this->ajaxReturn($arr);
					exit;
				} else {
					$msg = M("user")->where(array('id' => $user_id))->getField('username');
					$arr['status'] = 1;
					$arr['msg'] = $msg;
					$this->ajaxReturn($arr);
					exit;
				}
			}
		}

	}

	/**
	 * @param $id
	 * 根据自己的id查询出自身类型
	 * @return mixed
	 */
	public function getSelfType($id)
	{
		$m = D('member');
		return $m->where(array("id" => $id))->getField('usergrade');
	}

//	/**
//	 * 获取用户下级所有订单列表
//	 */
//	public function goods_orders2()
//	{
//		$m = M("goods_orders");
//		$id = I("get.id");
//		$model = M("member");
//		$arr = $model->select();
//		$newArr = array();
//		foreach ($arr as $k => $v) {
//			if (substr_count("@" . $v['path'] . "@", "@" . $id . "@")) {
//				$newArr[$k] = $v['id'];
//			}
//		}
//		$sqlStr = "";
//		foreach ($newArr as $v) {
//			$sqlStr .= "user_id=" . $v . " || ";
//		}
//		$sqlStr = rtrim($sqlStr, " || ");
//		$nowPage = isset($_GET['p']) ? $_GET['p'] : 1;
//		//实现带查询条件的分页,get方式传参
//		$num = $_REQUEST['keyword'];
//		$num = trim($num);
//		if ($num != "") {
//			$where = array('orders_num' => array("like", "%" . $num . "%"));//
//			//array('orders_num'=>array("like","%".$num."%" ));
//		} else {
//			if ($sqlStr == "") {
//				$this->display("user_orders");
//				exit;
//			}
//			$where = $sqlStr;
//
//
//		}
//		//dump($sqlStr);
//		// page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
//		$data = $m->order('id DESC')->where($where)->page($nowPage . ',' . PAGE_SIZE)->select();
//		//dump($m->getLastSql());echo111;
//		foreach ($data as $k => $v) {
//			$data[$k]['create_time'] = date('Y-m-d H:i:s', $data[$k]['create_time']);
//		}
//		//分页
//		$count = $m->where($where)->count();        // 查询满足要求的总记录数
//		//dump($m->getLastSql());
//		$page = new \Think\Page($count, PAGE_SIZE);        // 实例化分页类 传入总记录数和每页显示的记录数PAGE_SIZE
//		$page->parameter['mobile'] = $num;
//		$show = $page->show();        // 分页显示输出
//		$this->assign('page', $show);// 赋值分页输出
//		$this->assign("orders", $data);
//		//return array('page'=>$show,"orders"=>$data);
//		$this->display("user_orders");
//	}



	/**
	 * 用户购物车
	 */
	public function buy_car()
	{
		$m = M('goods_cart');
		$nowPage = isset($_GET['p']) ? $_GET['p'] : 1;
		// page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
		$id = $_REQUEST['id'];
		$where = array("user_id" => $id);
		$data = $m->where($where)->page($nowPage . ',' . PAGE_SIZE)->select();
		foreach ($data as $k => $v) {
			$data[$k]['create_time'] = date('Y-m-d H:i:s', $data[$k]['create_time']);
			$data[$k]['update_time'] = date('Y-m-d H:i:s', $data[$k]['update_time']);
		}
		//分页
		$count = $m->where($where)->count();        // 查询满足要求的总记录
		$page = new \Think\Page($count, PAGE_SIZE);        // 实例化分页类 传入总记录数和每页显示的记录数PAGE_SIZE
		$show = $page->show();        // 分页显示输出
		$this->assign('page', $show);// 赋值分页输出
		$this->assign('data', $data);
		$this->display();
	}
//	public function test(){
//		$m=M("member");
//		$arr=$m->select();
//		foreach($arr as $k=>$v){
//			$v['path']=str_replace("@","-",$v['path']);
//			$m->where(array("id"=>$k))->save(array("path"=>$v['path']));
//			echo $v['path']."<br/>";
//		}
//
//	}
	public function add_vip()
	{
		if (IS_AJAX) {
			$member = M("member");
			$history = M("user_review_history");
			$user = M("user");
			$admin = M("admin");
			$admin->startTrans();//开启事务,保证数据的完整性
			$grade_name = I("post.grade_name");
			$money = I("post.money");
			if ($grade_name == 1) {
				$grade_name = "合伙人";
				$endTime = (floor($money / 30000)) * 31622400 + (int)NOW_TIME;
			} else {
				$grade_name = "会员";
				$endTime = (floor($money / 365)) * 31622400 + (int)NOW_TIME;
			}
			$account = I("post.account");
			$true_name = I("post.trueName");
			$identityCard = I("post.identityCard");
			$sex=substr($identityCard,-2,1)%2==0?0:1;
			$email= I("post.email");
			$mobile= I("post.mobile");
			$kaihuhang= I("post.kaihuhang");
			$bankid= I("post.bankid");//in_time

			$addr= I("post.addr");
			$zip_code= I("post.zip_code");
			$town=I("post.town");
			$xian=M('cn_city')->where(array('cid'=>$town))->getField('cname');
			$pid=M('cn_city')->where(array('cid'=>$town))->getField('pid');
			$shi=M('cn_city')->where(array('cid'=>$pid))->getField('cname');
			$pid=M('cn_city')->where(array('cid'=>$pid))->getField('pid');
			$sheng=M('cn_city')->where(array('cid'=>$pid))->getField('cname');
			$addr=$sheng."省" .$shi."市".$xian." ".$addr;
			if (trim(I("post.pid")) === "" || I("post.pid")==1 || I("post.pid")==0) {
				$pid = $this->Public_pid;
			} else {
				$pid = trim(I("post.pid"));
			}
			$password = md5(I("post.password"));
			if(trim(I('post.in_time'))!=''){
				$create_time =strtotime(I('post.in_time'));
			}else{
				$create_time = NOW_TIME;
			}
			if ($admin->where(array("account" => $account))->count() > 0 || $member->where(array("mobile" => $account))->count() > 0 || $user->where(array("mobile" => $account))->count() > 0) {
				$this->error("账户" . $account . "已经存在!");
				exit;
			}
			$data = array("account" => $account, "password" => $password, "create_time" => $create_time, "status" => 0);
			$c = $admin->add($data);
			if (!$c) {
				$admin->rollback();
				$this->ajaxReturn(2);
				exit;
			}

			$user_id = $user->add(array("mobile" => $mobile, "create_time" => $create_time, "status" => 0, "password" => $password, "username" => $account,"admin_id"=>$c));
			if ($user_id == false) {
				$admin->rollback();
				$this->ajaxReturn(2);
				exit;
			}
			$a = $history->add(array("user_id" => $user_id, "reg_admin" => session('account')));
			$huifei = M("user_huifei");
			$b = $huifei->add(array("user_id" => $user_id, "huifei_money" => $money, "create_time" => NOW_TIME));
			$rst = $member->add(array("grade_name" => $grade_name, "mobile" => $mobile, "create_time" => $create_time, "status" => 0, "user_id" => $user_id,
				"true_name" => $true_name, "card_id" => $identityCard, "vip_end" => $endTime,"email"=>$email,"kaihuhang"=>$kaihuhang,
				"bankid"=>$bankid,"addr"=>$addr,"sex"=>$sex,"admin_id"=>$c,"zip_code"=>$zip_code));

				$path = $member->where(array('id'=>$pid))->getField('path');
			//$data = array();
			//$data['path'] = $path . $rst . '-';
			//$member->where(array('id' => $rst))->data($data)->save();
			$temp_path = $path . $rst . '-';
			$data=array("member_id"=>$rst,"pid" => $pid,'path'=>$temp_path);
			$d=M('member_cache')->add($data);
			file_put_contents('add.txt',M('member_cache')->getLastSql());
			if ($a && $b && $c && $d && $rst) {
				$admin->commit();
				$this->ajaxReturn(1);
			} else {
				$admin->rollback();
				$this->ajaxReturn(2);
				exit;
			}


		}
		$this->display();
	}

	public function review()
	{
		$m = M('user');
		$history = M("user_review_history");
		$admin = M("admin");
		$member = M("member");
		$user_id = I("post.user_id");
		$status = I("post.status");
		$password = I('post.password');
		$TruePassword = $admin->where(array("id" => session('aid')))->getField('password');
		$rec = $history->where(array("user_id" => $user_id))->getField('basic_admin');
		$checkId=$admin->where(array('account'=>$rec))->getField('id');
		$group_id=M('auth_group_access')->where(array('uid'=>$checkId))->getField('group_id');
		if (IS_AJAX) {
			if($status == 1 || $status == 3){
				if (md5($password) != $TruePassword) {
//				权限密码错误
					echo 8;
					exit;
				}
			}
			if ($status == 1) {
				//初审通过返回1
				$history->where(array("user_id" => $user_id))->save(array('basic_status' => 1, 'basic_time' => NOW_TIME, 'basic_admin' => session('account')));
				echo 1;
			} elseif ($status == 2) {
				//初审不通过返回2
				$history->where(array("user_id" => $user_id))->save(array('basic_status' => 2, 'basic_time' => NOW_TIME, 'basic_admin' => session('account')));
				echo 2;
			} elseif ($status == 3) {
				//复审通过
				if (($rec == session('account')) && $group_id!=30) {
					echo 7;
					exit;
				}
				$chu = $history->where(array("user_id" => $user_id))->getField('basic_status');
				if ($chu == 1 || $chu == 2) {
					$history->where(array("user_id" => $user_id))->save(array('last_status' => 1, 'last_time' => NOW_TIME, 'last_admin' => session('account')));
					//复审通过返回3
					$admin_id=$m->where(array('id'=>$user_id))->getField('admin_id');
					$mobile = $m->where(array("id" => $user_id))->getField('mobile');
					$admin->where(array("id" => $admin_id))->save(array('status' => 1));
					$member->where(array("user_id" => $user_id))->save(array('status' => 1));
					$m->where(array("id" => $user_id))->save(array('status' => 1));
					M('auth_group_access')->add(array('uid' => $admin_id, 'group_id' => $this->groupId));//分配到会员类别
					$money=M('user_huifei')->where(array("user_id" => $user_id))->getField('huifei_money');
					$grade_name=$member->where(array("user_id" => $user_id))->getField('grade_name');
					if($grade_name=='合伙人'){
						$pro_name='合伙人加盟费奖励';
					}else{
						$pro_name='会费';
					}
					R('Profit/changeCommion', array($user_id, 0, $money, $pro_name));
					$member_id=$this->getMid($user_id);
					$row=M('member_cache')->where(array('member_id'=>$member_id))->find();
					if($member->where(array('id'=>$member_id))->save(array('pid'=>$row['pid'],'path'=>$row['path']))){
						M('member_cache')->where(array('id'=>$member_id))->delete();
					}
					echo 3;
				} else {
					echo 5;//未进行初审返回5
				}

			} elseif ($status == 4) {
				//复审不通过

				if (($rec == session('account')) && $group_id!=30) {
					echo 7;
					exit;
				}
				$history->where(array("user_id" => $user_id))->save(array('last_status' => 2, 'last_time' => NOW_TIME, 'last_admin' => session('account')));
				echo 4;
			} else {
				echo 404;
			}
		} else {
			//$nowPage = isset($_GET['p'])?$_GET['p']:1;
			//实现带查询条件的分页,get方式传参
			$type = isset($_REQUEST['type']) ? $_REQUEST['type'] : 0;
			if ($type == 9) {
				$where = array('basic_status' => 0);//待初审
			} elseif ($type == 8) {
				$where = array('basic_status' => 1, 'last_status' => 0);//待复审
			} else {
				$where = array();
			}
			//$list = $history->where($where)->order('id desc')->page($nowPage.','.PAGE_SIZE)->select();
			$count = $history->where($where)->count();// 查询满足要求的总记录数
			$Page = new \Think\Page($count, PAGE_SIZE);// 实例化分页类 传入总记录数和每页显示的记录数
			$list = $history->where($where)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
			$show = $Page->show();// 分页显示输出$this->assign('page',$show);// 赋值分页输出
			$Page->parameter['type'] = $type;
			$this->assign('page', $show);// 赋值分页输出
			$this->assign('data', $list);
			$this->display();
		}
	}

	public function getUserInfo($user_id)
	{
		$userInfo = M("user")->where(array("id" => $user_id))->find();
		$account = M("user")->where(array("id" => $user_id))->getField("mobile");
		$adminInfo = M("admin")->where(array("account" => $account))->find();
		$memberInfo = M("member")->where(array("user_id" => $user_id))->find();
		$huifei = M("user_huifei")->where(array("user_id" => $user_id))->getField("huifei_money");
		$arr['user'] = $userInfo;
		$arr['admin'] = $adminInfo;
		$arr['member'] = $memberInfo;
		$arr['huifei'] = $huifei;
		return $arr;
	}

	public function shop_orders()
	{
		$m = M("goods_orders");
		$id = I("get.id");
		$nowPage = isset($_GET['p']) ? $_GET['p'] : 1;
		//实现带查询条件的分页,get方式传参
		$num = $_REQUEST['keyword'];
		$num = trim($num);
		if ($num != "") {
			$where = array('orders_num' => $num);
		} else {
			$where = array();
		}
		// page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
		$data = $m->order('id DESC')->where($where)->page($nowPage . ',' . PAGE_SIZE)->select();
		foreach ($data as $k => $v) {
			$data[$k]['create_time'] = date('Y-m-d H:i:s', $data[$k]['create_time']);
		}
		//分页
		$count = $m->where($where)->count();        // 查询满足要求的总记录数
		//dump($m->getLastSql());
		$page = new \Think\Page($count, PAGE_SIZE);        // 实例化分页类 传入总记录数和每页显示的记录数PAGE_SIZE
		$page->parameter['keyword'] = $num;
		$show = $page->show();        // 分页显示输出
		$this->assign('page', $show);// 赋值分页输出
		$this->assign("orders", $data);
		$this->display("user_orders");
	}



	public function ticheng_config()
	{
		$m = M('member_proportion');
		if (IS_POST) {
			$id = I("post.id");
			$first = I("post.first");
			$second = I("post.second");
			$third = I("post.third");
			$data['first'] = $first / 100;
			$data['second'] = $second / 100;
			$data['third'] = $third / 100;
			if ($m->where(array('id' => $id))->save($data)) {
				$this->success('修改成功', "", 5);
			} else {
				$this->error('修改失败,没有数据被更改....', "", 5);
			}
		} else {
			$data = $m->select();
			$this->assign("data", $data);
			$this->display();
		}
	}
	public function getCity(){

		$where=array('pid'=>$_GET['pid']);

		$arr=M('cn_city')->where($where)->select();
		echo json_encode($arr);
	}
	public function paihangbang(){
			$person=M('person_month','vip_');
			$user=M('user');
			$member=M('member','vip_');
			$limit=10;
			if(I('post.type')){
				$type=I('post.type');
			}else{
				$type=2;
			}
			if(I('post.mySelect')==2){
				//累计
				$rows=$person->select();
				$jihe=array();
				foreach($rows as $k=>$v){
					if(!in_array($v['member_id'],$jihe)){
						//$jihe[]=$v['member_id'];
					}
					
					$my=$user->where(array('id'=>$v['member_id']))->find();
					$add_hhr1_num=$person->where(array('member_id'=>$v['member_id']))->sum('add_hhr1_num');
					$add_hhr2_num=$person->where(array('member_id'=>$v['member_id']))->sum('add_hhr2_num');
					$add_hhr3_num=$person->where(array('member_id'=>$v['member_id']))->sum('add_hhr3_num');
					$add_hy1_num=$person->where(array('member_id'=>$v['member_id']))->sum('add_hy1_num');
					$add_hy2_num=$person->where(array('member_id'=>$v['member_id']))->sum('add_hy2_num');
					$add_hy3_num=$person->where(array('member_id'=>$v['member_id']))->sum('add_hy3_num');
					//if(!array_key_exists($rows[$k],$rows)){
						$rows[$k]['svip']=$add_hhr1_num+$add_hhr2_num+$add_hhr3_num;
						$rows[$k]['vip']=$add_hy1_num+$add_hy2_num+$add_hy3_num;
					//}
					
					/* $rows[$k]['realname']=$my['realname'];
					$rows[$k]['mobile']=$my['mobile']; */
				}
				foreach($rows as $k=>$v){
					$my=$user->where(array('id'=>$v['member_id']))->find();
					$grade_name=$member->where(array('id'=>$v['member_id']))->getField('grade_name');
					$jian=$v['member_id'];
					$jihe[$jian]['member_id']=$v['member_id'];
					$jihe[$jian]['vip']=$v['vip'];
					$jihe[$jian]['svip']=$v['svip'];
					$jihe[$jian]['realname']=$my['realname'];
					if($jihe[$jian]['realname']==''){
						$info=$member->where(array('id'=>$v['member_id']))->find();
						unset($map);
						$map['realname']=$info['true_name'];						
						$user->where(array('id'=>$id))->save($map);
						$jihe[$jian]['realname']=$info['true_name'];
					}
					$jihe[$jian]['mobile']=$my['mobile'];
					$jihe[$jian]['grade_name']=$grade_name;
				}
				//dump($jihe);exit;
				$rows=$jihe;
				foreach ($rows as $key=>$value){
					$svip[$key] = $value['svip'];
					$vip[$key] = $value['vip'];
				}			
				if($type==1){			
					array_multisort($svip,SORT_NUMERIC,SORT_DESC,$vip,SORT_NUMERIC,SORT_DESC,$rows);			
				}else{
					array_multisort($vip,SORT_NUMERIC,SORT_DESC,$svip,SORT_NUMERIC,SORT_DESC,$rows);			
				}
			}else{
				//分月
				if(I('post.yymm')){
					$yymm=I('post.yymm');
				$arr=explode('-',$yymm);

				$year=$arr[0];
				$month=$arr[1];
				}else{
				$year=date("Y",NOW_TIME);
				$month=date("m",NOW_TIME);
				}
				$rows=$person->where(array('year'=>$year,'month'=>$month))->select();
				foreach($rows as $k=>$v){
					$my=$user->where(array('id'=>$v['member_id']))->find();
					$rows[$k]['svip']=$v['add_hhr1_num']+$v['add_hhr2_num']+$v['add_hhr3_num'];
					$rows[$k]['vip']=$v['add_hy1_num']+$v['add_hy2_num']+$v['add_hy3_num'];
					$rows[$k]['realname']=$my['realname'];
					$grade_name=$member->where(array('id'=>$v['member_id']))->getField('grade_name');
					$rows[$k]['grade_name']=$grade_name;
					if($rows[$k]['realname']==''){
						$info=$member->where(array('id'=>$v['member_id']))->find();
						unset($map);
						$map['realname']=$info['true_name'];						
						$user->where(array('id'=>$v['member_id']))->save($map);
						//dump($user->getLastSql());
						$rows[$k]['realname']=$info['true_name'];
					}
					$rows[$k]['mobile']=$my['mobile'];
				}
				foreach ($rows as $key=>$value){
					$svip[$key] = $value['svip'];
					$vip[$key] = $value['vip'];
				}			
				if($type==1){			
					array_multisort($svip,SORT_NUMERIC,SORT_DESC,$vip,SORT_NUMERIC,SORT_DESC,$rows);			
				}else{
					array_multisort($vip,SORT_NUMERIC,SORT_DESC,$svip,SORT_NUMERIC,SORT_DESC,$rows);			
				}
			}
			

			//dump($rows);exit;
			$this->assign("rows", $rows);
			$this->assign("yy", $year);
			$this->assign("mm", $month);
			$this->assign("type", $type);
			if($year && $month){
				$this->assign("yymm", $year.'-'.$month);
			}
			$this->assign("mySelect", I('post.mySelect'));
			$this->display();
		
	}
	
	//添加供应商
	public function shoper_add(){
		if(IS_POST){
			$m = M('shoper');
			$where['mobile'] = $_POST['mobile'];
			$result = $m->where($where)->find();
			if(!empty($result)){
				$this->error('账户已存在,请更换账户重试');
			}
			$_POST['pwd'] = md5($_POST['pwd']);
			$_POST['create_time'] = time();
			if($m->add($_POST)){
				$this->success('添加成功');
			}else{
				$this->error('添加失败');
			}
		}else{
			$this->display();
		}
	}
	
	//供应商列表
	public function shoper_list(){
		$m = M('shoper');
		$nowPage = isset($_GET['p']) ? $_GET['p'] : 1;
		$result = $m->order('id DESC')->where($where)->page($nowPage . ',20')->select();
		$count = $m->where($where)->count();
		$page = new \Think\Page($count,20);        // 实例化分页类 传入总记录数和每页显示的记录数PAGE_SIZE
		$page->parameter['keyword'] = $num;
		$show = $page->show();        // 分页显示输出
		$this->assign('page', $show);// 赋值分页输出
		$this->assign('result', $result);
		$this->display();
	}
	

	//中奖记录
	public function choujiang_list(){
		$nowPage = isset($_GET['p']) ? $_GET['p']:1;

    	$begin_time = strtotime(date("Y-m-01"));
    	$end_time = strtotime(date('Y-m-01')." +1 month");

    	$where['create_time'] = array('between',"$begin_time,$end_time");		
		$m = M('choujiang');
		$result = $m->where($where)->order('id DESC')->page($nowPage.',20')->select();
		$this->assign('result', $result);

		$count = $m->where($where)->count();
		$page = new \Think\Page($count,20);        // 实例化分页类 传入总记录数和每页显示的记录数PAGE_SIZE
		$page->parameter['keyword'] = $num;
		$show = $page->show();        // 分页显示输出
		$this->assign('page', $show);// 赋值分页输出

		$this->display();
	}

	//设置奖品
	public function set_jiangpin(){
		if(IS_POST){
			$m = M('jiangpin');
			foreach ($_POST['id'] as $k => $v) {
				$where['id'] = $v['id'];
				$data['jiangpin_name'] = $_POST['jiangpin_name'][$k];
				$data['jiangpin_gailv'] = $_POST['jiangpin_gailv'][$k];
				$m->where($where)->save($data);
			}			
			$this->success('设置成功');
		}else{
			$m = M('jiangpin');
			$result = $m->order('id')->select();
			$this->assign('result',$result);

			$m2 = M('choujiang_xianzhi');
			$result2 = $m2->where('id=1')->find();
			$this->assign('result2',$result2);
			$this->display();
		}
	}

    /**
	    * 导出数据为excel表格
	    *@param $data    一个二维数组,结构如同从数据库查出来的数组
	    *@param $title   excel的第一行标题,一个数组,如果为空则没有标题
	    *@param $filename 下载的文件名
	    *@examlpe 
	    $stu = M ('User');
	    $arr = $stu -> select();
	    exportexcel($arr,array('id','账户','密码','昵称'),'文件名!');
	*/
	function exportexcel($data=array(),$title=array(),$filename='report'){
	    header("Content-type:application/octet-stream");
	    header("Accept-Ranges:bytes");
	    header("Content-type:application/vnd.ms-excel");  
	    header("Content-Disposition:attachment;filename=".$filename.".xls");
	    header("Pragma: no-cache");
	    header("Expires: 0");
	    //导出xls 开始
	    if (!empty($title)){
	        foreach ($title as $k => $v) {
	            $title[$k]=iconv("UTF-8", "GB2312",$v);
	        }
	        $title= implode("\t", $title);
	        echo "$title\n";
	    }
	    if (!empty($data)){
	        foreach($data as $key=>$val){
	            foreach ($val as $ck => $cv) {
	                $data[$key][$ck]=iconv("UTF-8", "GB2312", $cv);
	            }
	            $data[$key]=implode("\t", $data[$key]);
	            
	        }
	        echo implode("\n",$data);
	    }
	}
	
	//导出中奖记录
	public function daochu_choujiang_record(){
    	$begin_time = strtotime(date("Y-m-01"));
    	$end_time = strtotime(date('Y-m-01')." +1 month");

    	$where['choujiang_time'] = array('between',"$begin_time,$end_time");	

		$m = M('choujiang');
		$result = $m->where($where)->order('id DESC')->select();
		if(empty($result)){
			$this->error('没有数据可以导出');
		}
		$title[] = 'ID';
		$title[] = '中奖用户ID';
		$title[] = '中奖手机号';
		$title[] = '中奖时间';
    	$title[] = '中奖等级';
    	$title[] = '奖品名称';    	
    	$filename = '('.date("Y-m-01").'到'.date("Y-m-d",$end_time).')中奖记录';
    	$this->exportexcel($result,$title,$filename);
	}

	//设置抽奖限制积分
	public function xianzhi_jifen(){
		$data['xianzhi_jifen'] = $_POST['xianzhi_jifen'];
		$data['times'] = $_POST['times'];
		$m = M('choujiang_xianzhi');
		$result = $m->where('id=1')->save($data);
		if($result){
			$this->success('设置成功');
		}else{
			$this->error('设置失败');
		}
	}
	
}


